<?php
class CustomFieldController extends Zend_Controller_Action
{
	public function init()
	{
		Application_Helper_Authenticate::checkLogin($this);
	}

	public function indexAction()
	{
		$list = new Application_Model_DbTable_CustomField();

		$this->view->list = $list->fetchAll();
	}

	public function addAction()
	{
		$form  = new Application_Form_CustomField();

		$form->submit->setLabel('Add new CustomField');

		$this->view->form= $form;

		if ($this->getRequest()->isPost())
		{
			$formData = $this->getRequest()->getPost();

			if ($form->isValid($formData))
			{
				$mytoken = Application_Helper_Session::get('token', '');
				$token = $form->getValue('token');

				if($token == $mytoken)
				{
					Application_Helper_Session::remove('token');

					$data = $this->getRequest()->getParams();

					$customfield = new Application_Model_DbTable_CustomField();

					$customfield->createCustomField($data['name'], $data['type']);

					$this->_helper->redirector('index');
				}
				else
				{
					$this->_helper->redirector('index');
					//$form->populate($formData);
				}
			}
			else
			{
				$form->populate($formData);
			}
		}
		else
		{
			$values = array();
			$token = time();
			Application_Helper_Session::set('token', $token);

			$values['token'] = $token;

			$form->populate($values);

		}
	}

	public function updateAction()
	{
		$form  = new Application_Form_CustomField();

		$form->submit->setLabel('Update Field');

		$this->view->form= $form;

		if ($this->getRequest()->isPost())
		{
			$formData = $this->getRequest()->getParams();		
			
			$customfield = new Application_Model_DbTable_CustomField();
			$customfield->updateCustomField($formData['id'], $formData['name'], $formData['type']);

			$this->_helper->redirector('index');
		}
	}

	public function deleteAction()
	{
		if ($this->getRequest()->isPost()) {
			$del = $this->getRequest()->getPost('del');
			if ($del == 'Yes') {
				$id = $this->getRequest()->getPost('id');
				$customfield = new Application_Model_DbTable_CustomField();
				$customfield->removeCustomField($id);
			}
			$this->_helper->redirector('index');
		} else {
			$id = $this->_getParam('id', 0);
			$customfield = new Application_Model_DbTable_CustomField();
			$this->view->customfield = $customfield->getCustomField($id);
		}
	}
}